


import gulp from "gulp";
import lodash from "lodash";
import path from "path";

import goCommand from "./gocommand.js";

const basePath = path.join(__dirname, "../../");
const mainPackageName = "github.com/kore3lab/dashboard";


gulp.task(
  "backend",
  gulp.series((doneFn) => {
    goCommand(
      [
        "build",
        // Install dependencies to speed up subsequent compilations.
        // "-i",
        // for debugging backend
        "-gcflags=all=-N -l",
        "-o",
        path.join(basePath, ".tmp/serve/backend"),
        mainPackageName,
      ],
      doneFn
    );
  })
);


gulp.task(
  "backend:prod",
  gulp.series(() => {
    let outputBinaryPath = path.join(basePath, "dist", "amd64", "backend");
    return backendProd([[outputBinaryPath, "amd64"]]);
  })
);

/**
 * @param {!Array<!Array<string>>} outputBinaryPathsAndArchs array of
 *    (output binary path, architecture) pairs
 * @return {!Promise}
 */
function backendProd(outputBinaryPathsAndArchs) {
  let promiseFn = (path, arch) => {
    return (resolve, reject) => {
      goCommand(
        ["build", "-a", "-installsuffix", "cgo", "-o", path, mainPackageName],
        (err) => {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        },
        {
          // Disable cgo package. Required to run on scratch docker image.
          CGO_ENABLED: "0",
          GOARCH: arch,
        }
      );
    };
  };

  let goCommandPromises = outputBinaryPathsAndArchs.map(
    (pathAndArch) => new Promise(promiseFn(pathAndArch[0], pathAndArch[1]))
  );

  return Promise.all(goCommandPromises);
}
